package com.acme.mock;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.Scanner;

public class BankClient {

	Socket requestSocket;
	ObjectOutputStream out;
	String message;
	Scanner console;
	ObjectInputStream in;

	BankClient() {
	}

	void run() {
		try {
			requestSocket = new Socket("localhost", 2004);
			System.out.println("Connected to localhost in port 2004");
			out = new ObjectOutputStream(requestSocket.getOutputStream());
			out.flush();
			in = new ObjectInputStream(requestSocket.getInputStream());
			console = new Scanner(System.in);
			do {
				message = console.nextLine();
				System.out.println("server>" + message);
				sendMessage(message);
				Object recive = in.readObject();
				if (recive == null) {
					System.err.println();
				} else {
					System.out.println(recive.toString());
				}
			} while (!"bye".equals(message));
		} catch (UnknownHostException unknownHost) {
			System.err.println("You are trying to connect to an unknown host!");
		} catch (IOException ioException) {
			ioException.printStackTrace();
		} catch (ClassNotFoundException e) {
			System.err.println("Class cast exception");
		} finally {
			try {
				console.close();
				in.close();
				out.close();
				requestSocket.close();
			} catch (IOException ioException) {
				ioException.printStackTrace();
			}
		}
	}

	void sendMessage(final String msg) {
		try {
			out.writeObject(msg);
			out.flush();
		} catch (IOException ioException) {
			ioException.printStackTrace();
		}
	}

	public static void main(final String args[]) {
		BankClient client = new BankClient();
		client.run();
	}

}
